// $Id: account.js 331 2012-12-02 21:57:37Z bobcat $
// This file contains scripts to interact with the UltraCart API for login,
// logout, create user, change password, and form validation.

/*
 * Slide two HTML elements down, such that one becomes hidden and the other
 * shown.
 *
 * @param bottom - the element that will be hidden
 * @param top - the element that will be shown
 * @param amount - the amount to slide down by
 */
DSC.slideSwap = function ($bottom, $top, amount) {
  // simultaneously animate the two elements by sliding downwards
  $bottom.animate({
    top: '+=' + amount,
    opacity: '0'
  }, 210);
  $top.animate({
    top: '+=' + amount
  }, 210);
}

/*
 * Logout a customer and redirect them to the previous page.
 */
DSC.logout = function () {
	ultraCart.logoutCustomer();
  $('.logout a').attr('href', DSC.getReferrer());
  DSC.redirectAfter(DSC.getReferrer(), 3000);
};

/*
 * Login a customer. If successful, notify and redirect, otherwise display
 * some human readable errors to the user.
 *
 * @param email - the user's email
 * @param password - the user's password
 * @referrer - redirect to this URI
 */
DSC.login = function (email, password, referrer) {
  var $swapbox = $('#existing .swapbox'),
      $loading = $swapbox.find('.loading');
  // show loading gif
  $loading.css('opacity', 1);
  ultraCart.loginCustomer(email, password, {
    async: true,
    onComplete: function(result) {
      // finished request, hide the loading gif
      $loading.css('opacity', 0);
      if (result) {
        // success, change referrer link and notify the user of
        // iminent redirection
        $swapbox.find('.success a').attr('href', DSC.getReferrer());
        DSC.slideSwap($swapbox.find('form'), $swapbox.find('.success'), '13em');
        DSC.redirectAfter(DSC.getReferrer(), 3000);
      } else {
        // failure, notify the user
        $swapbox.find('#email').next().html('<label class="error">Verify email address.</label>');
        $swapbox.find('#password').next().html('<label class="error">Verify password.</label>');
      }
    }
  });
  return false;
};

/*
 * Reset a user's password. UltraCart will send an email to the user's address,
 * if valid.
 *
 * @param email - the user's email address.
 */
DSC.resetPassword = function (email) {
  var $swapbox = $('#reset .swapbox');
      $loading = $swapbox.find('.loading');
  // show loading gif
  $loading.css('opacity', 1);
  ultraCart.resetCustomerProfilePassword(email, {
    async: true,
    onComplete: function(result) {
      // finished, hide loading gif
      $loading.css('opacity', 0);
      if (result) {
        // notify user
        DSC.slideSwap($swapbox.find('form'), $swapbox.find('.success'), '13em');
      }
    }
  });
  return false;
};

/*
 * Create a user and log them in immediately. Redirect after 3 seconds.
 *
 * @param email - the new user's email.
 * @param password - the new user's password.
 */
DSC.createAccount = function (email, password) {
  var $swapbox = $('#create .swapbox'),
      $loading = $swapbox.find('.loading');
  // show loading gif
  $loading.css('opacity', 1);
  ultraCart.establishCustomerProfileImmediately(email, password, {
    async: true,
    onComplete: function(result) {
      // finished, hide loading gif
      $loading.css('opacity', 0);
      if (result) {
        // success, change referrer link and notify user of iminent redirection
        $swapbox.find('.success a').attr('href', DSC.getReferrer());
        DSC.slideSwap($swapbox.find('form'), $swapbox.find('.success'), '13em');
        DSC.redirectAfter(DSC.getReferrer(), 3000);
      } else {
        $swapbox.find('#new_email').next().html('<label class="error">Email address already registered.</label>');
      }
    }
  });
  return false;
};

/*
 * Behavior to be run when the page has fully loaded. Mainly validation rules
 * for the account access page's forms.
 */
$(document).ready(function() {
  // validation rules for login form
  $('#existing form').validate({
    rules: {
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 8
      }
    },
    messages: {
      email: {
        required: 'Please enter a valid email address.',
        email: 'Email address invalid.'
      },
      password: {
        required: 'Please enter your password.',
        minlength: 'Passwords are at least 8 characters.'
      }
    },
    errorPlacement: function(error, element) {
      // place errors directly next to their form elements
      element.next().html(error);
    },
    submitHandler: function(form) {
      // if validation is passed, log the user in
      DSC.login($('#email').val(), $('#password').val());
    }
  });

  // validation rules for create account form
  $('#create form').validate({
    rules: {
      new_email: {
        required: true,
        email: true
      },
      new_password: {
        required: true,
        minlength: 8
      },
      password_confirm: {
        required: true,
        minlength: 5,
        equalTo: '#new_password'
      }
    },
    messages: {
      new_email: {
        required: 'Please enter a valid email address.',
        email: 'Email address invalid.'
      },
      new_password: {
        required: 'Please enter a password.',
        minlength: 'Please enter at least 8 characters.'
      },
      password_confirm: {
        required: 'Repeat your password.',
        minlength: 'Please enter at least 8 characters.',
        equalTo: 'Passwords must match.'
      }
    },
    errorPlacement: function(error, element) {
      // place errors directly next to their form elements
      error.appendTo(element.next());
    },
    submitHandler: function(form) {
      // if valid, create a new account
      DSC.createAccount($('#new_email').val(), $('#password_confirm').val());
    }
  });

  // validation rules for reset password form
  $('#reset form').validate({
    rules: {
      reset_email: {
        required: true,
        email: true
      }
    },
    messages: {
      reset_email: {
        required: 'Please enter a valid email address.',
        email: 'Email address invalid.'
      }
    },
    errorPlacement: function(error, element) {
      // place errors directly next to their form elements
      error.appendTo(element.next());
    },
    submitHandler: function(form) {
      // if valid, dispatch password reset
      DSC.resetPassword($('#reset_email').val());
    }
  });
});